package com.java.service.Impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import com.java.mapper.PayMentMapper;
import com.java.model.order.*;
import com.java.model.refund.RefundStatusEnum;
import com.java.service.OrderService;
import com.java.service.PayMentInfoService;
import com.java.service.RefundInfoService;
import com.java.service.WeixinService;
import com.java.utils.ConstantPropertiesUtils;
import com.java.utils.HttpClient;
import org.bouncycastle.cms.PasswordRecipientId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class WeixinServiceImpl implements WeixinService {

   @Autowired
   private OrderService orderService;

   @Autowired
   private PayMentInfoService payMentInfoService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private PayMentMapper payMentMapper;

    @Autowired
    private RefundInfoService refundInfoService;

    //下单生成微信二维码
    @Override
    public Map createNative(Long orderId) {
        //去redis查询orderid是否有微信的二维码
        Map orderMap = (Map)redisTemplate.opsForValue().get(orderId.toString());
        if(orderMap!=null){
            return orderMap;
        }
        //1、根据orderId获取订单信息
        OrderInfo order = orderService.getById(orderId);
        //向支付记录中添加信息
        payMentInfoService.savePaymentInfo(order, PaymentTypeEnum.WEXIIN.getStatus());
        //设置参数 调用微信生成二维码接口
        Map paramMap = new HashMap();
        paramMap.put("appid", ConstantPropertiesUtils.APPID);
        paramMap.put("mch_id", ConstantPropertiesUtils.PARTNER);
        //生成一个唯一的随机字符串
        paramMap.put("nonce_str", WXPayUtil.generateNonceStr());
        //主体信息
        String body = order.getReserveDate() + "就诊"+ order.getDepname();
        paramMap.put("body", body);
        //订单编码
        paramMap.put("out_trade_no", order.getOutTradeNo());
        //paramMap.put("total_fee", order.getAmount().multiply(new BigDecimal("100")).longValue()+"");
        //订单的当前金额 为了测试统一写 1
        paramMap.put("total_fee", "1");//支付的金额
        //当前的ip地址
        paramMap.put("spbill_create_ip", "127.0.0.1");
        //回调地址
        paramMap.put("notify_url", "http://guli.shop/api/order/weixinPay/weixinNotify");
        //支付类型：扫码支付
        paramMap.put("trade_type", "NATIVE");

        //2、HttpClient 来根据URL访问第三方接口并传递参数
        HttpClient httpClient = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
        try {
            //client 设置参数 map集合设置成xml格式并且进行加密 ConstantPropertiesUtils.PARTNERKEY这是加密商户的key
            httpClient.setXmlParam(WXPayUtil.generateSignedXml(paramMap,ConstantPropertiesUtils.PARTNERKEY));
            httpClient.setHttps(true);
            httpClient.post();
            //返回第三方的数据 类型是xml
            String xml  = httpClient.getContent();

            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
            //4、封装返回结果集
            HashMap<String, Object> map = new HashMap<>();
            map.put("orderId",orderId);
            map.put("amount",order.getAmount());
            map.put("resultCode",resultMap.get("result_code"));
            map.put("codeUrl",resultMap.get("code_url"));//二维码路径
            //返回的接口保存到redis中
            redisTemplate.opsForValue().set(orderId.toString(),map,1000, TimeUnit.MINUTES);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //查询支付状态
    @Override
    public Map<String, String> queryPayStatus(Long orderId) {
        try {
            //1根据orderId获取订单
            OrderInfo order = orderService.getById(orderId);
            //2封装提交参数
            Map paramMap = new HashMap();
            paramMap.put("appid", ConstantPropertiesUtils.APPID);
            paramMap.put("mch_id", ConstantPropertiesUtils.PARTNER);
            paramMap.put("out_trade_no",order.getOutTradeNo());//订单编码
            paramMap.put("nonce_str", WXPayUtil.generateNonceStr());
            //3、设置请求内容
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
            client.setXmlParam(WXPayUtil.generateSignedXml(paramMap,ConstantPropertiesUtils.PARTNERKEY));
            client.setHttps(true);
            client.post();
            //4、得到数据返回接口
            String xml = client.getContent();//得到微信接口返回xml数据
            Map<String, String> contentMap = WXPayUtil.xmlToMap(xml);//xml转map

            return contentMap;

        }catch (Exception e){
            return null;
        }
    }

    //微信退款
    @Override
    public Boolean refund(Long orderId) {
        try {
        // 根据orderId 和 支付类型 获取支付记录信息
        QueryWrapper<PaymentInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("order_id",orderId);
        wrapper.eq("payment_type",PaymentTypeEnum.WEXIIN.getStatus());
        PaymentInfo paymentInfo = payMentMapper.selectOne(wrapper);
        //添加退款信息记录表
        RefundInfo refundInfo = refundInfoService.saveRefundInfo(paymentInfo);
        if(refundInfo.getRefundStatus().intValue() == RefundStatusEnum.REFUND.getStatus()){
            return true;
        }
        //退款
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("appid",ConstantPropertiesUtils.APPID);//公众账号ID
        paramMap.put("mch_id",ConstantPropertiesUtils.PARTNER);//商户编号
        paramMap.put("nonce_str",WXPayUtil.generateNonceStr());//随机字符串
        paramMap.put("transaction_id",paymentInfo.getTradeNo()); //微信订单号
        paramMap.put("trade_no",paymentInfo.getOutTradeNo());//商户订单编号
        paramMap.put("out_refund_no","tk"+paymentInfo.getOutTradeNo());//退款编号
        //paramMap.put("total_fee",paymentInfoQuery.getTotalAmount().multiply(new BigDecimal("100")).longValue()+"");
        //paramMap.put("refund_fee",paymentInfoQuery.getTotalAmount().multiply(new BigDecimal("100")).longValue()+"");
        //设置退款金额
        paramMap.put("total_fee","1");
        paramMap.put("refund_fee","1");

            String xml = WXPayUtil.generateSignedXml(paramMap, ConstantPropertiesUtils.PARTNER);//PARTNER:商户号

            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/secapi/pay/refund");
            client.setXmlParam(xml);
            client.setHttps(true);
            client.setCert(true);
            client.setCertPassword(ConstantPropertiesUtils.PARTNER);
            client.post();
            //返回第三方数据
            String xmlString = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xmlString);
            //如果退款成功
            if(null !=resultMap && WXPayConstants.SUCCESS.equalsIgnoreCase(resultMap.get("result_code"))){
                //设置回调时间和订单交易编号 resultMap.get("refund_id")
                refundInfo.setCallbackTime(new Date());
                refundInfo.setTradeNo(resultMap.get("refund_id"));
                refundInfo.setRefundStatus(RefundStatusEnum.REFUND.getStatus());
                refundInfo.setCallbackContent(JSONObject.toJSONString(resultMap));
                refundInfoService.updateById(refundInfo);
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}
